package com.lzx.reggie.service.impl

import com.baomidou.mybatisplus.core.toolkit.IdWorker
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.lzx.reggie.common.BaseContext
import com.lzx.reggie.common.CustomException
import com.lzx.reggie.entity.OrderDetail
import com.lzx.reggie.entity.Orders
import com.lzx.reggie.entity.ShoppingCart
import com.lzx.reggie.mapper.OrderMapper
import com.lzx.reggie.service.*
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.math.BigDecimal
import java.time.LocalDateTime
import java.util.concurrent.atomic.AtomicInteger


@Service
class OrderServiceImpl : ServiceImpl<OrderMapper, Orders>(), OrderService {
    companion object {
        private val log = LoggerFactory.getLogger(OrderServiceImpl::class.java)
    }

    @Autowired
    private lateinit var shoppingCartService: ShoppingCartService

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var addressBookService: AddressBookService

    @Autowired
    private lateinit var orderDetailService: OrderDetailService

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    override fun submit(orders: Orders) {
        //获得当前用户id
        val userId = BaseContext.currentId

        val wrapper = KtQueryWrapper(ShoppingCart::class.java).apply {
            eq(ShoppingCart::userId, userId)
        }
        // 查询当前用户的购物车数据
        val shoppingCarts = shoppingCartService.list(wrapper)
        if ((shoppingCarts?.size ?: 0) == 0) throw CustomException("购物车为空，不能下单")

        //查询用户数据
        val user = userService.getById(userId)

        //查询地址数据
        val addressBookId = orders.addressBookId
        val (_, _, consignee, phone, _, _, provinceName, _, cityName, _, districtName, detail) = addressBookService.getById(
            addressBookId
        ) ?: throw CustomException("用户地址信息有误，不能下单")

        //订单号
        val orderId = IdWorker.getId()

        val amount = AtomicInteger(0)

        val orderDetails = shoppingCarts
            .map { (_, name, _, dishId, setmealId, dishFlavor, number, amount1, image): ShoppingCart ->
                val orderDetail = OrderDetail()
                orderDetail.orderId = orderId
                orderDetail.number = number
                orderDetail.dishFlavor = dishFlavor
                orderDetail.dishId = dishId
                orderDetail.setmealId = setmealId
                orderDetail.name = name
                orderDetail.image = image
                orderDetail.amount = amount1
                amount.addAndGet(amount1!!.multiply(BigDecimal(number!!)).toInt())
                orderDetail
            }


        orders.id = orderId
        orders.orderTime = LocalDateTime.now()
        orders.checkoutTime = LocalDateTime.now()
        orders.status = 2
        orders.amount = BigDecimal(amount.get()) //总金额

        orders.userId = userId
        orders.number = orderId.toString()
        orders.userName = user.name
        orders.consignee = consignee
        orders.phone = phone
        orders.address = (provinceName ?: "") + (cityName ?: "") + (districtName ?: "") + (detail ?: "")

        //向订单表插入数据，一条数据
        save(orders)

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails)

        //清空购物车数据
        shoppingCartService.remove(wrapper)
    }
}